package com.dingceng.demo.base

import android.accounts.NetworkErrorException
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dingceng.demo.base.utils.log
import com.dingceng.demo.base.utils.toastCenter
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONException
import java.net.UnknownHostException
import java.net.UnknownServiceException

/**
 * 自定义ViewModel基类：
 * 1,抽取出常用字段：showLoading（控制显示加载UI）
 * 2,抽取协程中异常捕获器：handler（同意处理常见异常）
 */
open class BaseViewModel:ViewModel() {
    val showLoading = MutableLiveData(false)
    val handler:CoroutineExceptionHandler= CoroutineExceptionHandler { _, throwable ->
        throwable.printStackTrace()
        log("异常捕捉:${throwable.localizedMessage}")
        showLoading.postValue(false)
        var errorMessage = ""
        if (throwable is JSONException){
            errorMessage = "解析异常"
        }
        if (throwable is NetworkErrorException){
            errorMessage = "网络异常，请检查网络设置"
        }
        if (throwable is UnknownHostException){
            errorMessage = "网络异常，请检查网络设置"
        }
        if (throwable is UnknownServiceException){
            errorMessage = "服务器异常，请联系客服"
        }
        if (!errorMessage.isNullOrEmpty()){
            toastCenter(errorMessage)
        }
    }

}